package com.xcc.core.netty;


import com.xcc.core.netty.server.WebServerSocketHandler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;

public class WebSocketServer {

   private static Channel ch;
    
	private static void run(int port) {
		EventLoopGroup bossGroup=new NioEventLoopGroup();
		EventLoopGroup workerGroup=new NioEventLoopGroup();
		ServerBootstrap b=new ServerBootstrap();
		try {
			b.group(bossGroup,workerGroup)
			.channel(NioServerSocketChannel.class)
			.childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ChannelPipeline pipeline=ch.pipeline();
					pipeline.addLast("http-codec",new HttpServerCodec());
					pipeline.addLast("http-chunked",new ChunkedWriteHandler());
					pipeline.addLast("aggregator",new HttpObjectAggregator(65536));
					pipeline.addLast(new WebServerSocketHandler());
				}
			});
		    final ChannelFuture future=b.bind(port).sync() ;
			future.addListener(new ChannelFutureListener() {

				@Override
				public void operationComplete(ChannelFuture future) throws Exception {
					  if (future.isSuccess()) {
		                    System.out.println("服务器启动成功");
		                } else {
		                    System.out.println("服务器启动失败");
		                    future.cause().printStackTrace();
		                    workerGroup.shutdownGracefully();
		                }
				}
			});
			  ch=future.channel();
			ch.closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}




	public static void main(String[] args) {
        run(5555);
    }








}
